package com.orgcent.tuangou.xml;

import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public abstract class AbstractHandler extends DefaultHandler {

	// 公共数据的存放类，所有数据都从这里取，一般将它写在Const类中，这里我就不建Const.java了
	public static Map<String, Object> hash = new HashMap<String, Object>();// 放在Const.java中！

	public abstract boolean parse(String xmlString);
	public abstract boolean parse(InputStream is);

	public static void parserXml(AbstractHandler baseHandler, String xmlString)
			throws Exception {
		if (xmlString == null || xmlString.length() == 0)
			return;

		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		XMLReader xr = parser.getXMLReader();
		/* 设置自定义的MyHandler给XMLReader */
		xr.setContentHandler(baseHandler);
		// 创建一个xml字符串
		StringReader read = new StringReader(xmlString);
		try {
			// 创建新的输入源SAX 解析器将使用 InputSource对象来确定如何读取 XML 输入
			xr.parse(new InputSource(read));
		} finally {
			read.close();
		}
	}

	public static void parserXml(InputStream is,AbstractHandler baseHandler)
			throws Exception {

		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		XMLReader xr = parser.getXMLReader();
		/* 设置自定义的MyHandler给XMLReader */
		xr.setContentHandler(baseHandler);
		xr.parse(new InputSource(is));
		parser = null;
	}

	public abstract void characters(char[] ch, int start, int length)
			throws SAXException;

	public abstract void endDocument() throws SAXException;

	public abstract void endElement(String uri, String localName, String qName)
			throws SAXException;

	public abstract void startDocument() throws SAXException;

	public abstract void startElement(String uri, String localName,
			String qName, Attributes attributes) throws SAXException;
}
